package com.lovo.bbs.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.naming.NamingException;

import com.lovo.bbs.po.RegisterPo;
import com.lovo.bbs.util.DbUtil;
import com.lovo.bbs.util.MysqlDb;

/**
 * 注册Dao
 * @author tiancen2001
 *
 */
public class RegisterDao {
	public RegisterDao (){
		
	}

	/**
	 * 添加用户
	 * @param rp
	 * @return 1:注册成功, 0:用户已存在, -1:异常
	 * @throws NamingException
	 * @throws SQLException
	 */
	public  int addUser(RegisterPo rp) throws NamingException, SQLException {
		
		MysqlDb mysqldb = new MysqlDb();
		mysqldb.setPool(true);
		Connection con = DbUtil.getConn(mysqldb);
		
		int added=0;
		
		//先查询用户是否已存在
		String sqlExsist = "select userid from user where username='"+rp.getUsername()+"'";
		ResultSet rsExisist=con.prepareStatement(sqlExsist).executeQuery();
		if(rsExisist.next()){//若用户已存在
			mysqldb.closeRS(rsExisist);
			mysqldb.closeConnection(con);
			return 0;
		}
		
		//添加用户
		String sql="insert into user  " +
				" (username, password, email, " +
				" qq, msn, blog, homepage, birthday, home) " +
				" values" +
				" ( ?,?, ?, " +
				"?, ?, ?, ?, ?,?)";
		PreparedStatement ps = con.prepareStatement(sql);
		
		//必填项
		ps.setString(1, rp.getUsername());
		ps.setString(2, rp.getPassword());
		ps.setString(3, rp.getEmail());
		
		//选填项
		if(!"".equals(rp.getQq())){
			ps.setString(4,rp.getQq());
		}else{
			ps.setString(4,null);
		}
		if(!"".equals(rp.getMsn())){
			ps.setString(5,rp.getMsn());
		}else{
			ps.setString(5,null);
		}
		if(!"".equals(rp.getBlog())){
			ps.setString(6,rp.getBlog());
		}else{
			ps.setString(6,null);
		}
		if(!"".equals(rp.getHomePage())){
			ps.setString(7,rp.getHomePage());
		}else{
			ps.setString(7,null);
		}
		if(rp.getBirthday().length()>2){
			ps.setString(8,rp.getBirthday());
		}else{
			ps.setString(8,null);
		}
		if(!"".equals(rp.getHome())){
			ps.setString(9,rp.getHome());
		}else{
			ps.setString(9,null);
		}
		
		int result=ps.executeUpdate();
		if(result==1){
			added=1;
		}
		mysqldb.closeRS(rsExisist);
		mysqldb.closePS(ps);
		
		mysqldb.closeConnection(con);
		return added;
	}

}
